package cn.yunbamboos.rest.service.handler;

import cn.yunbamboos.rest.service.RestServiceExchange;
import cn.yunbamboos.rest.service.core.DefaultRestServiceExchange;
import cn.yunbamboos.rest.service.filter.FilterChain;
import cn.yunbamboos.rest.service.filter.RestServiceFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;

public class FilteringHandler {

    private static final Logger logger = LoggerFactory.getLogger(FilteringHandler.class);

    public void handle(List<RestServiceFilter> combined, DefaultRestServiceExchange exchange) {
        Collections.sort(combined);

        if (logger.isDebugEnabled()) {
            logger.debug("rest service filter : {}", combined);
        }

        new DefaultFilterChain(combined).filter(exchange);
    }

    private static class DefaultFilterChain implements FilterChain {

        private final int index;

        private final List<RestServiceFilter> filters;

        DefaultFilterChain(List<RestServiceFilter> filters) {
            this.filters = filters;
            this.index = 0;
        }

        private DefaultFilterChain(DefaultFilterChain parent, int index) {
            this.filters = parent.getFilters();
            this.index = index;
        }

        public List<RestServiceFilter> getFilters() {
            return filters;
        }

        @Override
        public void filter(RestServiceExchange exchange) {
            if (this.index < filters.size()) {
                RestServiceFilter filter = filters.get(this.index);
                DefaultFilterChain chain = new DefaultFilterChain(this, this.index + 1);
                filter.filter(exchange, chain);
            }
        }

    }

}
